package com.redis.demo.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @author cici
 */
@RestController
public class GoodController9 {

    final String REDIS_LOCK = "ciciLock";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private Redisson redisson;

    @GetMapping(value = "/miaosha")
    public String goods(){

        String value = UUID.randomUUID().toString()+Thread.currentThread().getName();

        RLock rLock = redisson.getLock(REDIS_LOCK);
        rLock.lock();

        try {
            String res = redisTemplate.opsForValue().get("goods:001");
            int num = res == null ? 0 : Integer.parseInt(res);
            if (num > 0){
                int afterNum = num - 1 ;
                redisTemplate.opsForValue().set("goods:001",String.valueOf(afterNum));
                System.out.println("成功购买商品，库存还剩下：" + afterNum + "，端口来自" + serverPort);
                return "成功购买商品，库存还剩下：" + afterNum + "，端口来自" + serverPort;
            }else {
                System.out.println("商品已售罄。" + serverPort);
            }
            return "商品已售罄。" + serverPort;
        }finally {
            if (rLock.isLocked() && rLock.isHeldByCurrentThread()){
                rLock.unlock();
            }
        }

    }
}
